#-*-coding:utf-8-*-
#!/usr/bin/env python
'''
Created on 2009/9/14

@author: chenhh
'''

"""
   multiprocessing version
"""

import MySQLdb
import time, decimal, os
from multiprocessing import Process, Queue, Lock
from Queue import Empty
from cStringIO import StringIO
from const import database
###################################################
outputfile="../../SMA_MP.csv"
###################################################
def buildallStockSMA_MP():
    
    #db connection
    sql_id="select stock_id from company"
    dbconn = MySQLdb.connect(host=database.MYSQL_HOST, \
                         user=database.MYSQL_USER, \
                         passwd=database.MYSQL_PWD, \
                         db=database.MYSQL_DB)

    dbcursor = dbconn.cursor()
    dbcursor.execute(sql_id)
    stockid_list=dbcursor.fetchall()
    
    #full of queue
    work_queue = Queue()
    [work_queue.put(id) for id in stockid_list]
  
    #start working 
    time_start = time.time()
    write_lock = Lock()
    processes = [Process(target=buildSMA_MP, args=(work_queue, write_lock)) for i in range(4)]
    for p in processes: p.start()
    for p in processes: p.join()
    print "total time: %.3f secs"%(time.time()-time_start)
###################################################
def buildSMA_MP(queue, write_lock): 
    while True:
        try:
            id = queue.get(block=False)
            sql="select stock_id, date, close_price from transaction where stock_id='%s' order by date ASC"%id
            #db connection
            dbconn = MySQLdb.connect(host=database.MYSQL_HOST, \
                         user=database.MYSQL_USER, \
                         passwd=database.MYSQL_PWD, \
                         db=database.MYSQL_DB)
            dbcursor = dbconn.cursor()
            dbcursor.execute(sql)
            recordset = dbcursor.fetchall()
            strio = StringIO()
            #print "id=%s, record len = %s"%(id,len(recordset))
            totaltime1 = time.time()
            
            #計算day SMA
            for day in xrange(2, 31):
                t1 = time.time()
                smasum = 0
                for (idx, line) in enumerate(recordset):
                    #此版本在day大時，計算量太大
                    #smasum = sum(recordset[jdx][2] for jdx in xrange(idx-day+1, idx+1) if idx > day)
                    #修正版，加入最新一天的值，減去最舊一天的值
                    if idx < day: 
                        smasum += recordset[idx][2]
                        continue
                    smasum += recordset[idx][2]
                    smasum -= recordset[idx-day][2]
                    print >>strio, "%s, %s, %.3f, SMA%s"%(line[0], line[1], smasum/day, day)
                    #print "%s, %s, %.3f, SMA%s, SMAsum: %s"%(line[0], line[1], smasum/day, day, smasum)
                    
                t2 = time.time()
                print "pid = %s, stock id:%s, SMA:%s complete, %.3f secs"\
                    %(os.getpid(), line[0], day, (t2-t1))
                
                #write StringIO to file
                write_lock.acquire()
                output = open(outputfile, 'a')
                print >>output, strio.getvalue()
                output.close()
                write_lock.release()
        
        except Empty:
            break
                
###################################################
if __name__ == '__main__':
    buildallStockSMA_MP()